package controller.transform;

import javax.vecmath.Vector3d;

import component.Ball;
import component.Status;
import component.Tube;
import component.group.ComponentGroup;

public class AlignToTube extends AlignMode {

	private Ball pivot;
	private Tube alignWith = null;
	
	
	public AlignToTube(Gui gui, Scene scene, Ball pivot) {
		super(gui, scene, pivot);
		this.pivot = pivot;
	}

	@Override
	protected void tubeClicked(Tube tube) {
		if (alignWith == null) {
			alignWith = tube;
			alignWith.setStatus(Status.SELECTED, true);
			this.setDefaultText();
		} else {
			align(tube);
		}
	}

	private void align(Tube tube) {
		ComponentGroup group = this.makeSelection(tube);
		if (group == null) return;
		if (group.contains(alignWith)) {
			gui.setStatusText("Unable to align tubes, as they are connected.");
			return;
		}
		
		Vector3d tubeVector = tube.getOrientation().getVector();
		Vector3d alignTo = alignWith.getOrientation().getVector();
		
		alignGroup(group, this.getClosestRotation(tubeVector, alignTo), pivot.getPos());		
	}

	@Override
	protected void setDefaultText() {
		if (alignWith == null) {
			gui.setStatusText("Select tube to align.");
		} else {
			gui.setStatusText("Select reference tube.");
		}

	}
	
	@Override
	public void deselected() {
		super.deselected();
		if (alignWith != null) {
			alignWith.setStatus(Status.NORMAL);
		}
	}

}
